const Watcher = require('./watcher');

class Compile {
	constructor(el, vm) {
		this.vm = vm;
		const ele = document.querySelector(el);
		this.fragment = document.createDocumentFragment();
		this.fragment.append(ele);
		this.replace(this.fragment);
		document.body.appendChild(this.fragment);
	}

	replace(frag) {
		Array.from(frag.childNodes).forEach(node => {
			if (node.nodeType === 3) {
				const replaceTxt = (item) => {
					const keyArr = item.split('.');
					let data = null;
					keyArr.forEach(key => {
						if (!data) return data = this.vm[key];
						return data = data[key];
					});
					node.textContent = txt.replace(reg, data).trim();
				};

				const txt = node.textContent;
				const reg = /\{\{(.*?)\}\}/g;
				let arrMatch = txt.match(reg);
				if(!arrMatch) return;
				arrMatch = arrMatch.map(item => item.slice(2, -2));

				arrMatch.forEach(item => {
					replaceTxt(item);
					this.vm.$notice.sub(new Watcher(item, replaceTxt));
				})

			}

			if (node.nodeType === 1) {
				const nodeAttr = node.attributes;
				Array.from(nodeAttr).forEach(item => {
					let name = item.name;
					let exp = item.value;
					// 如果属性有 v-
					if (name.includes('v-')) {
						let keyArr = exp.split('.');
						let data = null;
						keyArr.forEach(key => {
							if (!data) return data = this.vm[key];
							return data = data[key];
						});
						node.value = data;
						node.addEventListener('input', e => {
							const preArr = keyArr.slice(0, keyArr.length - 1);
							const end = keyArr[keyArr.length - 1];
							const tem = preArr.reduce((pre, cur) => pre[cur], this.vm);
							tem[end] = e.target.value;
						});
					}
				});
			}

			if (node.childNodes && node.childNodes.length) {
				this.replace(node);
			}
		});
	}
}

module.exports = Compile;